<template>
  <div class="Assignment">
    <el-card>
      <div class="Assignment_top">
        <el-button @click="handlerGoBack" type="primary">返回上一级</el-button>
        <!-- <el-button icon="el-icon-setting" type="primary" @click="saveSetting">保存设置</el-button> -->
      </div>
      <h2 class="assignmentName">{{ assifnmentName }}</h2>
      <el-table
        :data="assifnmentList"
        style="width: 95%;margin-top: 20px;"
        row-key="id"
        border
        ref="Table"
        :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
        :select-on-indeterminate="false"
        @select="select"
        @select-all="selectAll"
        @selection-change="selectionChange"
        :header-cell-style="{
          width: '100%',
          background: '#FAFAFA',
          color: '#606266',
          height: '60px'
        }"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="导航名称"></el-table-column>
        <el-table-column prop="PermissionType" label="权限" width="650">
          <template slot-scope="scoped">
            <div>
              <span v-if="scoped.row.PermissionType == null" style="color:red"
                >暂无数据</span
              >
              <el-tag v-if="scoped.row.PermissionType == 1"
                >总后台端权限</el-tag
              >
              <el-tag type="success" v-if="scoped.row.PermissionType == 2"
                >商户端权限</el-tag
              >
              <el-tag type="info" v-if="scoped.row.PermissionType == 3"
                >加盟端权限</el-tag
              >
              <el-tag type="warning" v-if="scoped.row.PermissionType == 4"
                >客户移动端权限</el-tag
              >
              <el-tag type="danger" v-if="scoped.row.PermissionType == 5"
                >加盟移动端权限</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="权限名称">
          <template slot-scope="scoped">
            <div>
              <el-tag
                type="success"
                v-if="scoped.row.distribute == 2"
                style="margin-right:15px;cursor:pointer"
                >未分配</el-tag
              >
              <el-tag
                type="danger"
                v-if="scoped.row.distribute == 1"
                style="margin-right:15px;cursor:pointer"
                >已分配</el-tag
              >

              <el-button
                type="warning"
                v-else-if="
                  scoped.row.distribute == 2 && scoped.row.child != undefined
                "
                size="small"
                style="margin-right:15px;"
                @click="handlerrolePowerAdd(scoped.row.id, scoped.row)"
                :disabled="havebuttonDisabled"
                >分配权限</el-button
              >
              <el-button
                type="danger"
                v-if="scoped.row.distribute == 1"
                size="small"
                style="margin-right:15px;"
                @click="
                  handlerrolePowerDel(scoped.row.userRolePowerId, scoped.row.id)
                "
                >删除权限</el-button
              >
            </div>
          </template>
        </el-table-column>

        <!-- <el-table-column prop="name" label="权限资源">
          <template>
            <div>
              <el-checkbox
                :indeterminate="isIndeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
                style="float:left;margin-right:10px;"
              >全选</el-checkbox>
              <el-checkbox-group
                v-model="assignments"
                @change="handleCheckedassignChange"
                style="float:left"
              >
                <el-checkbox>添加</el-checkbox>
                <el-checkbox>删除</el-checkbox>
                <el-checkbox>修改</el-checkbox>
                <el-checkbox>分佣</el-checkbox>
              </el-checkbox-group>
            </div>
          </template>
        </el-table-column>-->
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="assifnmentQuery.pageSize"
          :current-page="assifnmentQuery.pageNumber"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
          class="management_page"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
import { roleSelPower, rolePowerAdd, rolePowerdel } from "../../utils/api";
export default {
  data() {
    return {
      // 权限数据
      assifnmentList: [],
      //   全选的状态
      checkAll: false,
      //   被选中的数据
      assignments: [],
      isIndeterminate: true,
      // 权限分配的列表
      assifnmentQuery: {
        pageNumber: 1,
        pageSize: 10,
        userRoleId: "",
        roleId: "",
        PermissionType: ""
      },
      // 噶管理员的名字
      assifnmentName: "",
      // 总条数
      count: 0,
      // 用户id
      userId: "",
      // 按钮的禁用
      havebuttonDisabled: false,
      nobuttonDisabled: false,
      buttonDisabled: false,
      isAllSelect: false,
      selectArr: [],
      powerIdarr: []
    };
  },
  methods: {
    // 返回上一级
    handlerGoBack() {
      this.$store.dispatch("delVisitedViews", this.$route).then(obj => {
        this.$router.push("/PersionRole");
      });
    },
    // 点击保存设置
    // saveSetting() {
    //   this.$confirm("eaw ?", "是否退出重新登录?", {
    //     closeOnClickModal: false,
    //     confirmButtonText: "退出登录",
    //     cancelButtonText: "返回上级",
    //     type: "warning"
    //   })
    //     .then(() => {
    //       this.$router.push("/Login");
    //     })
    //     .catch(() => {
    //       this.$router.go(-1);
    //     });
    // },
    // 获取权限分配列表
    getAssifnment() {
      this.postRequest(roleSelPower, this.assifnmentQuery).then(res => {
        if (res.code == 200) {
          this.assifnmentList = res.data.data;
          this.count = res.data.count;
          const result = res.data.data;
          // for(var i=0;i<result.length;i++){
          //   result[i]['show']=2;
          // }

          // result.forEach(item => {
          //   if (item.distribute == 2) {
          //     this.havebuttonDisabled = false;
          //     console.log(item);
          //     for (var i = 0; i < item.child.length; i++) {
          //       // if (item.distribute == 2) {
          //       //   this.nobuttonDisabled = true;
          //       // }
          //     }
          //   }
          // });
        }
      });
    },
    // 分配权限的函数
    handlerrolePowerAdd(powerId, data) {
      const powerarr = this.selectArr.join(",");
      const params = {
        roleId: this.assifnmentQuery.roleId,
        userId: this.userId,
        powerId: powerarr
      };
      //  if(data.parentId==0){
      //    this.buttonDisabled=true
      //  }
      this.$confirm("此操作是分配权限,你确定要分配吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          this.postRequest(rolePowerAdd, params).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "分配成功,请重新登录!"
              });
              this.getAssifnment();
            } else if (res.code == 400) {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消分配"
          });
        });
    },
    // 删除权限
    handlerrolePowerDel(id, powerId) {
      // const params = {
      //   roleId: this.assifnmentQuery.roleId,
      //   userId: this.userId,
      //   id: id,
      //   powerId: powerId
      // };
      const powerarr = this.powerIdarr.join(",");
      const params = {
        userId: this.userId,
        id: powerarr,
        roleId: this.assifnmentQuery.roleId
      };
      // console.log(params);
      this.$confirm("此操作是删除权限,确定删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          this.postRequest(rolePowerdel, params).then(res => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getAssifnment();
            } else if (res.code == 400) {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 分页
    handleSizeChange(val) {
      this.assifnmentQuery.pageSize = val;
      this.getAssifnment();
    },
    handleCurrentChange(val) {
      this.assifnmentQuery.pageNumber = val;
      this.getAssifnment();
    },
    // // 点击表格中复选框拿到父类id
    // handleSelectionChange(val) {
    //   if (val.length > 1) {
    //    this.$refs.Table.clearSelection();
    //    this.$refs.Table.toggleRowSelection(val.pop());
    //   }
    // },
    // // 单选
    // choosperssionChange(val) {
    //  this.$refs.Table.toggleRowSelection(val);
    // },
    select(selection, row) {
      if (
        selection.some(el => {
          return row.id === el.id;
        })
      ) {
        if (row.child) {
          row.child.map(j => {
            this.toggleSelection(j, true);
          });
        }
      } else {
        if (row.child) {
          row.child.map(j => {
            this.toggleSelection(j, false);
          });
        }
      }
    },
    selectAll(selection) {
      // assifnmentList第一层只要有在selection里面就是全选
      const isSelect = selection.some(el => {
        const assifnmentListIds = this.assifnmentList.map(j => j.id);
        return assifnmentListIds.includes(el.id);
      });
      // tableDate第一层只要有不在selection里面就是全不选
      const isCancel = !this.assifnmentList.every(el => {
        const selectIds = selection.map(j => j.id);
        return selectIds.includes(el.id);
      });
      if (isSelect) {
        selection.map(el => {
          if (el.child) {
            el.child.map(j => {
              this.toggleSelection(j, true);
            });
          }
        });
      }
      if (isCancel) {
        this.assifnmentList.map(el => {
          if (el.child) {
            el.child.map(j => {
              this.toggleSelection(j, false);
            });
          }
        });
      }
    },
    selectionChange(selection) {
      // 拿到权限id 和父级的权限id
      const resultarr = [];
      selection.map(v => {
        // , v.parentId
        resultarr.push(v.id);
      });
      // 拿到权限powerId
      const rowpowerArr = [];
      selection.map(v => {
        rowpowerArr.push(v.userRolePowerId);
      });
      this.powerIdarr = rowpowerArr;
      var newArr = new Set(resultarr); //_ddd数组形式不能直接使用
      // 通过array.from方式来使用
      var fin = Array.from(newArr);
      this.selectArr = fin;
      // console.log(this.selectArr);
      var index = this.selectArr.indexOf(0);
      //大于0 代表存在，
      if (index > -1) {
        //存在就删除
        this.selectArr.splice(index, 1);
      }
    },
    toggleSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.Table && this.$refs.Table.toggleRowSelection(row, select);
        });
      }
    },
    cancelAll() {
      this.$refs.Table.clearSelection();
    }
    // // 点击全选触发的事件
    // handleCheckAllChange() {},
    // //点击单选框触发的事件
    // handleCheckedassignChange() {}
  },
  created() {
    // 获取用户信息
    const userInfo = JSON.parse(window.sessionStorage.getItem("userInfo"));
    // 拿到用户登录的角色id
    this.assifnmentQuery.userRoleId = userInfo.roleId;
    // 拿到用户id
    this.userId = userInfo.id;
    // 拿到角色id
    this.assifnmentQuery.roleId = window.sessionStorage.getItem("roleId");
    // 拿到角色名字
    this.assifnmentName = window.sessionStorage.getItem("roleName");
    // 拿到PermissionType
    this.assifnmentQuery.PermissionType = window.sessionStorage.getItem(
      "PermissionType"
    );

    this.getAssifnment();
  }
};
</script>
<style lang="less" scoped>
.Assignment {
  .assignmentName {
    margin-top: 20px;
    width: 94%;
    padding: 10px;
    border: 1px solid #ebeef5;
  }
}
</style>
